<?php if(!class_exists("View", false)) exit("no direct access allowed");?><main class="container mx-auto px-4 pt-24 pb-16">
        <!-- 欢迎区域 -->
        <section class="mb-10">
            <div class="bg-gradient-to-r from-ocean-100 to-secondary/10 rounded-2xl p-6 md:p-8">
                <div class="flex flex-col md:flex-row items-center justify-between">
                    <div class="mb-6 md:mb-0">
                        <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-dark mb-2">欢迎回来，<?php echo htmlspecialchars($_kp_realname, ENT_QUOTES, "UTF-8"); ?>！</h2>
                        <p class="text-gray-600 mb-4 max-w-2xl">今天是 <span id="current-date" class="font-medium"></span>，你有  <?php echo htmlspecialchars($notificationCount, ENT_QUOTES, "UTF-8"); ?> 个通知需要查看。</p>
                        <div class="flex flex-wrap gap-3">
                            <button id="addApp" class="bg-ocean-500 text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 hover:bg-ocean-600 focus:ring-2 focus:ring-ocean-400 focus:outline-none">
                                <i class="fa fa-plus mr-2"></i>添加应用
                            </button>
                        </div>
                    </div>
                    <div class="w-full md:w-auto">
                        <img src="https://picsum.photos/id/180/600/300" alt="应用统计图表" class="rounded-lg shadow-md max-w-full h-auto">
                    </div>
                </div>
            </div>
        </section>

        <!-- 最近使用的应用 -->
        <section class="mb-10">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-xl font-bold text-dark">最近使用</h2>
                <a href="#" class="text-ocean-500 hover:underline text-sm font-medium">查看全部</a>
            </div>
            
            <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
                <!-- 应用卡片 -->
                 <?php if(!empty($usage)){ $_foreach_us_counter = 0; $_foreach_us_total = count($usage);?><?php foreach( $usage as $us ) : ?><?php $_foreach_us_index = $_foreach_us_counter;$_foreach_us_iteration = $_foreach_us_counter + 1;$_foreach_us_first = ($_foreach_us_counter == 0);$_foreach_us_last = ($_foreach_us_counter == $_foreach_us_total - 1);$_foreach_us_counter++;?>
                <div class="bg-white rounded-xl shadow-sm p-4 app-card-hover">
                    <div class="h-12 w-12 bg-<?php echo htmlspecialchars($us['color_bg'], ENT_QUOTES, "UTF-8"); ?>-100 rounded-lg flex items-center justify-center mb-3">
                        <i class="fa <?php echo htmlspecialchars($us['appImg'], ENT_QUOTES, "UTF-8"); ?> text-<?php echo htmlspecialchars($us['color_font'], ENT_QUOTES, "UTF-8"); ?>-500 text-xl"></i>
                    </div>
                    <h3 class="font-medium text-dark mb-1"><?php echo htmlspecialchars($us['appName'], ENT_QUOTES, "UTF-8"); ?></h3>
                    <p class="text-xs text-gray-500"><?php echo htmlspecialchars($us['appDesc'], ENT_QUOTES, "UTF-8"); ?></p>
                </div>
                <?php endforeach; }?>

            </div>
        </section>

        <!-- 应用分类 -->
        <section class="mb-10">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-xl font-bold text-dark">应用分类</h2>
                <div class="flex space-x-2">
                    <button class="category-btn px-3 py-1 text-sm rounded-full bg-ocean-500 text-white">全部</button>
                    <!-- <button class="category-btn px-3 py-1 text-sm rounded-full bg-gray-200 text-gray-700 hover:bg-gray-300 transition-colors">办公</button>
                    <button class="category-btn px-3 py-1 text-sm rounded-full bg-gray-200 text-gray-700 hover:bg-gray-300 transition-colors">娱乐</button>
                    <button class="category-btn px-3 py-1 text-sm rounded-full bg-gray-200 text-gray-700 hover:bg-gray-300 transition-colors">社交</button>
                    <button class="category-btn px-3 py-1 text-sm rounded-full bg-gray-200 text-gray-700 hover:bg-gray-300 transition-colors">工具</button> -->
                </div>
            </div>
            
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                <!-- 应用组卡片 -->
                <?php if(!empty($categories)){ $_foreach_cate_counter = 0; $_foreach_cate_total = count($categories);?><?php foreach( $categories as $cate ) : ?><?php $_foreach_cate_index = $_foreach_cate_counter;$_foreach_cate_iteration = $_foreach_cate_counter + 1;$_foreach_cate_first = ($_foreach_cate_counter == 0);$_foreach_cate_last = ($_foreach_cate_counter == $_foreach_cate_total - 1);$_foreach_cate_counter++;?>
                <div class="bg-white rounded-xl shadow-sm overflow-hidden">
                    <div class="h-3 bg-<?php echo htmlspecialchars($cate['color_bg'], ENT_QUOTES, "UTF-8"); ?>-500"></div>
                    <div class="p-5">
                        <div class="flex items-center justify-between mb-4">
                            <h3 class="font-bold text-dark"><?php echo htmlspecialchars($cate['category_name'], ENT_QUOTES, "UTF-8"); ?></h3>
                            <span class="text-xs bg-<?php echo htmlspecialchars($cate['color_bg'], ENT_QUOTES, "UTF-8"); ?>-100 text-<?php echo htmlspecialchars($cate['color_bg'], ENT_QUOTES, "UTF-8"); ?>-500 px-2 py-1 rounded-full"><?php echo htmlspecialchars($cate['appCount'], ENT_QUOTES, "UTF-8"); ?> 个应用</span>
                        </div>
                        
                        <div class="grid grid-cols-4 gap-3">
                            <?php if(!empty($cate['apps'])){ $_foreach_app_counter = 0; $_foreach_app_total = count($cate['apps']);?><?php foreach( $cate['apps'] as $app ) : ?><?php $_foreach_app_index = $_foreach_app_counter;$_foreach_app_iteration = $_foreach_app_counter + 1;$_foreach_app_first = ($_foreach_app_counter == 0);$_foreach_app_last = ($_foreach_app_counter == $_foreach_app_total - 1);$_foreach_app_counter++;?>
                            <div class="text-center app-card-hover">
                                <div onclick="redirectToApp('<?php echo htmlspecialchars($app['appUrl'], ENT_QUOTES, "UTF-8"); ?>','<?php echo htmlspecialchars($app['id'], ENT_QUOTES, "UTF-8"); ?>','<?php echo htmlspecialchars($uid, ENT_QUOTES, "UTF-8"); ?>')" class="h-10 w-10 mx-auto bg-<?php echo htmlspecialchars($app['color_bg'], ENT_QUOTES, "UTF-8"); ?>-100 rounded-lg flex items-center justify-center mb-2">
                                    <i class="fa <?php echo htmlspecialchars($app['appImg'], ENT_QUOTES, "UTF-8"); ?> text-<?php echo htmlspecialchars($app['color_font'], ENT_QUOTES, "UTF-8"); ?>-600"></i>
                                </div>
                                <span class="text-xs text-gray-700"><?php echo htmlspecialchars($app['appName'], ENT_QUOTES, "UTF-8"); ?></span>
                            </div>
                            <?php endforeach; }?>
                            
                            <div class="text-center app-card-hover">
                                <div class="h-10 w-10 mx-auto bg-gray-100 rounded-lg flex items-center justify-center mb-2">
                                    <i class="fa fa-plus text-gray-600"></i>
                                </div>
                                <span class="text-xs text-gray-700">更多</span>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; }?>
                
            </div>
        </section>

        <!-- 热门应用 -->
        <section class="mb-10">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-xl font-bold text-dark">热门应用</h2>
                <a href="#" class="text-ocean-500 hover:underline text-sm font-medium">查看全部</a>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <!-- 大型应用卡片 -->
                <?php if(!empty($hotlist)){ $_foreach_hot_counter = 0; $_foreach_hot_total = count($hotlist);?><?php foreach( $hotlist as $hot ) : ?><?php $_foreach_hot_index = $_foreach_hot_counter;$_foreach_hot_iteration = $_foreach_hot_counter + 1;$_foreach_hot_first = ($_foreach_hot_counter == 0);$_foreach_hot_last = ($_foreach_hot_counter == $_foreach_hot_total - 1);$_foreach_hot_counter++;?>
                <div class="bg-white rounded-xl shadow-sm overflow-hidden app-card-hover">
                    <div class="relative h-40">
                        <img src="<?php echo htmlspecialchars($hot['bg_img'], ENT_QUOTES, "UTF-8"); ?>" alt="文件管理应用" class="w-full h-full object-cover">
                        <div class="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent"></div>
                        <div class="absolute bottom-3 left-3">
                            <span class="text-xs bg-<?php echo htmlspecialchars($hot['color_bg'], ENT_QUOTES, "UTF-8"); ?>-500 text-white px-2 py-1 rounded-full"><?php echo htmlspecialchars($hot['categoryName'], ENT_QUOTES, "UTF-8"); ?></span>
                        </div>
                    </div>
                    <div class="p-5">
                        <div class="flex items-start justify-between">
                            <div>
                                <h3 class="font-bold text-dark mb-1"><?php echo htmlspecialchars($hot['appName'], ENT_QUOTES, "UTF-8"); ?></h3>
                                <p class="text-sm text-gray-600 mb-3"><?php echo htmlspecialchars($hot['appDesc'], ENT_QUOTES, "UTF-8"); ?></p>
                            </div>
                            <div class="flex items-center">
                                <i class="fa fa-star text-yellow-400"></i>
                                <span class="ml-1 text-sm font-medium"><?php echo htmlspecialchars($hot['appScore'], ENT_QUOTES, "UTF-8"); ?></span>
                            </div>
                        </div>
                        <div class="flex items-center justify-between pt-3 border-t border-gray-100">
                            <div class="flex items-center">
                                <img src="https://picsum.photos/id/1001/100/100" alt="开发者头像" class="h-8 w-8 rounded-full object-cover">
                                <span class="ml-2 text-xs text-gray-600">技术团队</span>
                            </div>
                            <!-- <button class="text-xs bg-ocean-100 text-ocean-500 px-3 py-1 rounded-full hover:bg-ocean-200 transition-colors">
                                <i class="fa fa-plus mr-1"></i>添加
                            </button> -->
                        </div>
                    </div>
                </div>
                <?php endforeach; }?>
                
            </div>
        </section>

        <!-- 应用使用统计 -->
        <section>
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-xl font-bold text-dark">应用使用统计</h2>
                <div class="flex space-x-2">
                    <button class="time-filter-btn px-3 py-1 text-sm rounded-lg bg-ocean-500 text-white">本周</button>
                    <button class="time-filter-btn px-3 py-1 text-sm rounded-lg bg-gray-200 text-gray-700 hover:bg-gray-300 transition-colors">本月</button>
                    <button class="time-filter-btn px-3 py-1 text-sm rounded-lg bg-gray-200 text-gray-700 hover:bg-gray-300 transition-colors">全年</button>
                </div>
            </div>
            
            <div class="bg-white rounded-xl shadow-sm p-6">
                <div class="h-64">
                    <canvas id="appUsageChart"></canvas>
                </div>
            </div>
        </section>

        <!-- 添加应用弹出框 -->
        <div id="add-app-modal" class="fixed inset-0 z-50 hidden bg-black bg-opacity-50 flex items-center justify-center">
            <div class="bg-white rounded-xl shadow-2xl p-8 w-96 relative">
                <span id="close-modal" class="absolute top-3 right-3 text-gray-600 hover:text-gray-800 cursor-pointer">
                    <i class="fa fa-times"></i>
                </span>
                <h2 class="text-2xl font-bold text-dark mb-6 text-center">添加应用</h2>
                <form id="add-app-form">
                    <div class="mb-6">
                        <label for="app-name" class="block text-sm font-medium text-gray-700 mb-1">应用名称</label>
                        <input type="text" id="app-name" class="input-field w-full" required>
                    </div>
                    <div class="mb-6">
                        <label for="app-description" class="block text-sm font-medium text-gray-700 mb-1">应用描述</label>
                        <textarea id="app-description" class="input-field w-full" rows="3"></textarea>
                    </div>
                    <div class="mb-6">
                        <label for="app-icon" class="block text-sm font-medium text-gray-700 mb-1">应用图标</label>
                        <div class="relative">
                            <input type="text" id="app-icon-display" class="input-field w-full" readonly>
                            <div id="app-icon-dropdown" class="absolute top-full left-0 right-0 bg-white border border-gray-300 rounded-lg mt-1 hidden max-h-48 overflow-y-auto">
                                <!-- 这里会通过 JavaScript 动态添加 Font Awesome 图标选项 -->
                            </div>
                        </div>
                    </div>
                    <div class="mb-6">
                        <label for="app-category" class="block text-sm font-medium text-gray-700 mb-1">应用分类</label>
                        <div id="app-category-dropdown" class="relative">
                            <input type="text" id="app-category-display" class="input-field w-full" readonly>
                            <div id="app-category-options" class="absolute top-full left-0 right-0 bg-white border border-gray-300 rounded-lg mt-1 hidden max-h-48 overflow-y-auto">
                                <!-- 这里会通过 JavaScript 动态添加分类选项 -->
                            </div>
                        </div>
                    </div>
                    <div class="mb-6">
                        <label for="app-developer" class="block text-sm font-medium text-gray-700 mb-1">应用开发者</label>
                        <input type="text" id="app-developer" class="input-field w-full">
                    </div>
                    <div class="mb-6">
                    <label for="app-type" class="block text-sm font-medium text-gray-700 mb-1">应用类型</label>
                        <select id="app-type" class="input-field w-full" required>
                            <option value="1">内页应用</option>
                            <option value="2">外部链接应用</option>
                        </select>
                    </div>
                    <div class="mb-6">
                        <label for="app-url" class="block text-sm font-medium text-gray-700 mb-1">应用入口页面地址</label>
                        <input type="text" id="app-url" class="input-field w-full" required>
                    </div>
                    <div class="flex justify-center space-x-6">
                        <button type="button" id="cancel-add-app" class="btn-secondary">取消</button>
                        <button type="submit" id="submit-add-app" class="btn-primary">提交</button>
                    </div>
                </form>
            </div>
        </div>

    </main>

    <!-- JavaScript -->
    <script>
        function redirectToApp(apiUrl,appid,uid) {
            const appurl = `${apiUrl}?id=${appid}&uid=${uid}`
            window.open(appurl, '_blank');
            $.get('<?php echo url(array('c'=>"system", 'a'=>"useageadd", ));?>?appid='+appid,function(data){})
        }
        // 显示 Toast 提示的函数
        function showToast(message, type = 'info') {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.style.opacity = 1;

            // 根据类型设置背景颜色
            switch (type) {
                case 'success':
                    toast.style.backgroundColor = '#00B42A';
                    break;
                case 'error':
                    toast.style.backgroundColor = '#F53F3F';
                    break;
                case 'warning':
                    toast.style.backgroundColor = '#FF7D00';
                    break;
                default:
                    toast.style.backgroundColor = '#333';
            }

            // 自动隐藏 Toast
            setTimeout(() => {
                toast.style.opacity = 0;
            }, 3000);
        }
        const apiUrl = 'https://lhappsapi.renbenzhihui.com';
        // 设置当前日期
        const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
        const currentDate = new Date().toLocaleDateString('zh-CN', options);
        document.getElementById('current-date').textContent = currentDate;
        
        // 移动端菜单切换
        $('#mobile-menu-button').on('click', function() {
            $('#mobile-menu').toggleClass('hidden');
        });

        $('#logout-link').click(function(event) {
            event.preventDefault();
            localStorage.removeItem('token');
            // 刷新当前页面
            location.reload();
        });

        // 滚动时导航栏样式变化
        $(window).on('scroll', function() {
            if ($(window).scrollTop() > 10) {
                $('#header').addClass('shadow-md bg-white/95 backdrop-blur-sm');
            } else {
                $('#header').removeClass('shadow-md bg-white/95 backdrop-blur-sm');
            }
        });
        
        // 分类按钮切换
        $('.category-btn').on('click', function() {
            $('.category-btn').removeClass('bg-ocean-500 text-white');
            $('.category-btn').addClass('bg-gray-200 text-gray-700');
            $(this).removeClass('bg-gray-200 text-gray-700');
            $(this).addClass('bg-ocean-500 text-white');
        });

        // 获取用户头像和下拉菜单元素
        const userAvatar = $('#user-avatar');
        const userDropdown = $('#user-dropdown');

        // 为用户头像添加点击事件监听器
        userAvatar.on('click', function() {
            // 切换下拉菜单的显示状态
            userDropdown.toggleClass('hidden');
        });

        // 为文档添加点击事件监听器，当点击文档其他区域时隐藏下拉菜单
        $(document).on('click', function(event) {
            if (!$(userAvatar).is(event.target) && !$(userAvatar).has(event.target).length && !$(userDropdown).is(event.target) && !$(userDropdown).has(event.target).length) {
                $(userDropdown).addClass('hidden');
            }
        });

        // 检查用户登录状态
        const token = localStorage.getItem('token')?localStorage.getItem('token'):false;
        
        const userInfo = $('#user-info');
        const notification = $('#notification');
        const userProfile = $('#user-profile');
        const loginButton = $('#login-button');

        if (token) {
            // 用户已登录，调用接口获取用户信息
            $.ajax({
                url: `${apiUrl}/user/getUser.html`,
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                success: function(response) {
                    // console.log(response);
                    // 更新用户头像和用户名
                    const userAvatar = userProfile.find('img');
                    const userName = userProfile.find('span');
                    userAvatar.attr('src', response.data.user.avatar);
                    userAvatar.on('error', function() {
                        $(this).attr('src', 'https://picsum.photos/id/1005/200/200');
                    });
                    // 通用脱敏函数
                    function desensitize(str) {
                        if (!str) return '';
                        const phoneReg = /^1[3-9]\d{9}$/;
                        if (phoneReg.test(str)) {
                            return str.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
                        }
                        return str;
                    }
                    userName.text(desensitize(response.data.user.nickname));
                    const notificationCount = $('#notification-count');
                    if (response.data.notifications > 0) {
                        notificationCount.text(response.data.notifications).show();
                    } else {
                        notificationCount.hide();
                    }

                    // 显示用户信息和通知
                    notification.show();
                    userProfile.show();
                    loginButton.hide();
                },
                error: function(error) {
                    console.error('获取用户信息失败:', error);
                    // 显示登录按钮
                    notification.hide();
                    userProfile.hide();
                    loginButton.show();
                }
            });
        } else {
            // 用户未登录，显示登录按钮
            notification.hide();
            userProfile.hide();
            loginButton.show();
        }
        $('#login-button').on('click',function(){
            window.location.href = `/login.html`;
        })
        // 时间筛选按钮切换
        $('.time-filter-btn').on('click', function() {
            $('.time-filter-btn').removeClass('bg-ocean-500 text-white');
            $('.time-filter-btn').addClass('bg-gray-200 text-gray-700');
            $(this).removeClass('bg-gray-200 text-gray-700');
            $(this).addClass('bg-ocean-500 text-white');
            
            // 更新图表数据
            updateChart($(this).text());
        });
        
        $(document).ready(function() {
            // 点击添加应用按钮，显示弹出框
            $('#addApp').on('click', function() {
                location.href='/system/appsindex'
            });

            // 点击关闭图标或取消按钮，隐藏弹出框
            $('#close-modal, #cancel-add-app').on('click', function() {
                $('#add-app-modal').addClass('hidden');
            });

            // 动态添加 Font Awesome 图标选项
            const fontAwesomeIcons = [
                "fa-calendar", "fa-tasks", "fa-envelope", "fa-file-text", "fa-bar-chart",
                "fa-file-word-o", "fa-file-excel-o", "fa-file-powerpoint-o", "fa-file-pdf-o",
                "fa-code", "fa-database", "fa-github", "fa-terminal", "fa-bug",
                "fa-facebook", "fa-twitter", "fa-instagram", "fa-whatsapp", "fa-youtube-play", "fa-linkedin",
                "fa-home", "fa-user", "fa-users", "fa-lock", "fa-unlock",
                "fa-search", "fa-cog", "fa-wrench", "fa-trash", "fa-check",
                "fa-times", "fa-plus", "fa-minus", "fa-info-circle", "fa-exclamation-circle",
                "fa-star", "fa-star-o", "fa-heart", "fa-heart-o", "fa-comment",
                "fa-comments", "fa-phone", "fa-map-marker", "fa-globe", "fa-clock-o",
                "fa-money", "fa-credit-card", "fa-shopping-cart", "fa-tag", "fa-tags",
                "fa-print", "fa-download", "fa-upload", "fa-cloud", "fa-cloud-download",
                "fa-cloud-upload", "fa-fire", "fa-bolt", "fa-leaf", "fa-tree",
                "fa-picture-o", "fa-camera", "fa-video-camera", "fa-music", "fa-headphones",
                "fa-gamepad", "fa-plane", "fa-car", "fa-bus", "fa-train",
                "fa-ship", "fa-bicycle", "fa-motorcycle", "fa-wheelchair", "fa-blind",
                "fa-deaf", "fa-child", "fa-male", "fa-female", "fa-group",
                "fa-building", "fa-hospital-o", "fa-school", "fa-bank", "fa-library",
                "fa-camera-retro", "fa-coffee", "fa-cutlery", "fa-beer", "fa-glass",
                "fa-birthday-cake", "fa-gift", "fa-trophy", "fa-flag", "fa-flag-o",
                "fa-ban", "fa-eye", "fa-eye-slash", "fa-exchange", "fa-arrows",
                "fa-arrows-h", "fa-arrows-v", "fa-expand", "fa-compress", "fa-angle-left",
                "fa-angle-right", "fa-angle-up", "fa-angle-down", "fa-chevron-left", "fa-chevron-right",
                "fa-chevron-up", "fa-chevron-down", "fa-caret-left", "fa-caret-right", "fa-caret-up",
                "fa-caret-down"
            ];

            const iconDropdown = $('#app-icon-dropdown');
            fontAwesomeIcons.forEach(icon => {
                const option = `<div class="px-4 py-2 hover:bg-gray-100 cursor-pointer" data-icon="${icon}">
                                    <i class="fa ${icon} mr-2"></i> ${icon.replace('fa-', '')}
                                </div>`;
                iconDropdown.append(option);
            });

            // 点击图标输入框，显示下拉框
            $('#app-icon-display').on('click', function() {
                $('#app-icon-dropdown').toggleClass('hidden');
            });

            // 点击下拉框中的图标选项，选择图标并隐藏下拉框
            $('#app-icon-dropdown').on('click', 'div', function() {
                const selectedIcon = $(this).data('icon');
                $('#app-icon-display').val(selectedIcon);
                $('#app-icon-dropdown').addClass('hidden');
            });

            // 点击页面其他地方，隐藏下拉框
            $(document).on('click', function(e) {
                if (!$('#app-icon-display').is(e.target) && !$('#app-icon-dropdown').is(e.target) && $('#app-icon-dropdown').has(e.target).length === 0) {
                    $('#app-icon-dropdown').addClass('hidden');
                }
            });

            // 从服务端接口获取应用分类数据
            function getAppCategories() {
                $.ajax({
                    url: `${apiUrl}/pub/getAppCategories.html`, // 替换为实际的接口地址
                    method: 'GET',
                    success: function(response) {
                        const categoryOptions = $('#app-category-options');
                        categoryOptions.empty();
                        // 递归生成多级分类下拉列表
                        function generateCategoryOptions(categories, level = 0) {
                            categories.forEach(category => {
                                const indent = '&nbsp;'.repeat(level * 4);
                                const option = `<div class="px-4 py-2 hover:bg-gray-100 cursor-pointer" data-id="${category.id}">
                                                    ${indent}${category.name}
                                                </div>`;
                                categoryOptions.append(option);
                                if (category.children && category.children.length > 0) {
                                    generateCategoryOptions(category.children, level + 1);
                                }
                            });
                        }
                        generateCategoryOptions(response);
                    },
                    error: function(error) {
                        alert('获取应用分类数据失败，请稍后重试。');
                    }
                });
            }

            // 点击分类输入框，显示下拉框
            $('#app-category-display').on('click', function() {
                $('#app-category-options').toggleClass('hidden');
            });

            // 点击下拉框中的分类选项，选择分类并隐藏下拉框
            $('#app-category-options').on('click', 'div', function() {
                const selectedCategoryId = $(this).data('id');
                const selectedCategoryName = $(this).text().trim();
                $('#app-category-display').val(selectedCategoryName);
                $('#app-category-display').data('category-id', selectedCategoryId);
                $('#app-category-options').addClass('hidden');
            });

            // 点击提交按钮，模拟调用服务端接口添加应用
            $('#add-app-form').on('submit', function(e) {
                e.preventDefault();

                // 获取表单数据
                const appName = $('#app-name').val();
                const appDescription = $('#app-description').val();
                const appIcon = $('#app-icon-display').val();
                const categoryId = $('#app-category-display').data('category-id');
                const developer = $('#app-developer').val();
                const appType = $('#app-type').val();
                const appUrl = $('#app-url').val();
                // 验证应用名称、应用图标和应用分类是否为空
                if (!appName || !appIcon || !categoryId || !appType|| !appUrl) {
                    showToast('应用名称、应用类型、应用入口页面地址、应用图标和应用分类是必填项，请填写完整。', 'error');
                    return;
                }

                // 模拟服务端接口调用
                $.ajax({
                    url: `${apiUrl}/app/AddApp.html`, // 模拟接口地址
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    data: {
                        app_name: appName,
                        app_description: appDescription,
                        app_icon: appIcon,
                        category_id: categoryId,
                        developer: developer,
                        app_type: appType,
                        app_url: appUrl,
                    },
                    success: function(response) {
                        if (response.status/1 === 0) {
                            showToast(response.msg, 'success');
                        } else {
                            showToast(response.msg, 'error');
                        }
                        $('#add-app-modal').addClass('hidden');
                        $('#add-app-form')[0].reset();
                    },
                    error: function(error) {
                        showToast('应用添加失败，请稍后重试。', 'error');
                    }
                });
            });
        });
        // 首页应用使用次数统计
        function getAppUseage(timePeriod){
            $.get(`/system/getAppUseage?period=`+timePeriod,function(data){
                // 初始化图表
                const ctx = document.getElementById('appUsageChart').getContext('2d');
                const appUsageChart = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: data.data.labels,
                        datasets: [{
                            label: '使用次数',
                            data: data.data.usage_data,
                            backgroundColor: [
                                'rgba(22, 93, 255, 0.7)',
                                'rgba(15, 198, 194, 0.7)',
                                'rgba(0, 180, 42, 0.7)',
                                'rgba(255, 125, 0, 0.7)',
                                'rgba(245, 63, 63, 0.7)',
                                'rgba(156, 39, 176, 0.7)',
                                'rgba(255, 213, 79, 0.7)'
                            ],
                            borderColor: [
                                'rgba(22, 93, 255, 1)',
                                'rgba(15, 198, 194, 1)',
                                'rgba(0, 180, 42, 1)',
                                'rgba(255, 125, 0, 1)',
                                'rgba(245, 63, 63, 1)',
                                'rgba(156, 39, 176, 1)',
                                'rgba(255, 213, 79, 1)'
                            ],
                            borderWidth: 1,
                            borderRadius: 6
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                                titleColor: '#1D2129',
                                bodyColor: '#4E5969',
                                borderColor: '#E5E6EB',
                                borderWidth: 1,
                                padding: 12,
                                boxPadding: 6,
                                usePointStyle: true,
                                callbacks: {
                                    label: function(context) {
                                        return `使用次数: ${context.raw}`;
                                    }
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                grid: {
                                    color: 'rgba(0, 0, 0, 0.05)'
                                },
                                ticks: {
                                    precision: 0
                                }
                            },
                            x: {
                                grid: {
                                    display: false
                                }
                            }
                        },
                        animation: {
                            duration: 1000,
                            easing: 'easeOutQuart'
                        }
                    }
                });
            })
        }
        getAppUseage("week");
        



        
        
        // 更新图表数据
        function updateChart(timePeriod) {
            let data = [];
            
            if (timePeriod === '本周') {
                // data = [18, 15, 12, 10, 8, 6, 5];
                getAppUseage("week");
            } else if (timePeriod === '本月') {
                // data = [65, 59, 40, 45, 30, 25, 20];
                getAppUseage("month");
            } else if (timePeriod === '全年') {
                // data = [250, 220, 180, 160, 140, 120, 100];
                getAppUseage("year");
            }
            
            appUsageChart.data.datasets[0].data = data;
            appUsageChart.update();
        }
        
        // 应用卡片悬停效果增强
        $('.app-card-hover').on('mouseenter', function() {
            $(this).addClass('shadow-lg');
            $(this).find('i').addClass('animate-pulse');
        }).on('mouseleave', function() {
            $(this).removeClass('shadow-lg');
            $(this).find('i').removeClass('animate-pulse');
        });
    </script>